package com.ihai.spring.boot.sample.interceptor;

import org.apache.catalina.connector.CoyoteOutputStream;
import org.apache.catalina.connector.OutputBuffer;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.nio.ByteBuffer;

/**
 * DESC
 *
 * @author Adolphus
 * @date 2018/10/18
 */
public class ResponseInterceptor implements HandlerInterceptor {
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        // 截取响应流
        CoyoteOutputStream os = (CoyoteOutputStream) httpServletResponse.getOutputStream();
        // 取到流对象对应的Class对象
        Class<CoyoteOutputStream> c = CoyoteOutputStream.class;
        // 取出流对象中的OutputBuffer对象，该对象记录响应到客户端的内容
        Field fs = c.getDeclaredField("ob");
        if (fs.getType().toString().endsWith("OutputBuffer")) {
            fs.setAccessible(true);// 设置访问ob属性的权限
            OutputBuffer ob = (OutputBuffer) fs.get(os);// 取出ob
            Class<OutputBuffer> cc = OutputBuffer.class;
            Field ff = cc.getDeclaredField("bb");// 取到OutputBuffer中的输出流
            ff.setAccessible(true);
            if (ff.getType().toString().endsWith("ByteBuffer")) {
                ByteBuffer bb = (ByteBuffer) ff.get(ob);// 取到byte流
                System.out.println(new String(bb.array(),"UTF-8"));
            }
        }
    }
}
